extends CharacterBody2D
class_name Player

# 玩家属性
var speed: float = 150.0
var direction: Vector2 = Vector2.UP
var can_shoot: bool = true

# 坦克等级和生命值
var level: int = 1
var health: int = 1

# 精灵纹理
var up_textures = [
	preload("res://assets/Images/Player1/50x50/UP1.png"),
	preload("res://assets/Images/Player1/50x50/UP2.png")
]
var down_textures = [
	preload("res://assets/Images/Player1/50x50/DOWN1.png"),
	preload("res://assets/Images/Player1/50x50/DOWN2.png")
]
var left_textures = [
	preload("res://assets/Images/Player1/50x50/LEFT1.png"),
	preload("res://assets/Images/Player1/50x50/LEFT2.png")
]
var right_textures = [
	preload("res://assets/Images/Player1/50x50/RIGHT1.png"),
	preload("res://assets/Images/Player1/50x50/RIGHT2.png")
]

# 动画相关
var animation_timer: float = 0.0
var animation_speed: float = 0.2
var current_frame: int = 0

# 节点引用
@onready var sprite = $Sprite2D
@onready var collision_shape = $CollisionShape2D
@onready var shoot_timer = $ShootTimer

# 信号
signal player_died
signal player_shot(bullet_pos: Vector2, direction: Vector2)

func _ready():
	# 设置碰撞形状
	var shape = RectangleShape2D.new()
	shape.size = Vector2(50, 50)
	collision_shape.shape = shape
	
	# 连接射击计时器
	shoot_timer.timeout.connect(_on_shoot_timer_timeout)
	
	# 设置初始方向
	update_sprite()

func _physics_process(delta):
	if not can_move():
		return
	
	handle_input()
	handle_animation(delta)
	move_and_slide()

func can_move() -> bool:
	# 检查游戏状态等
	return true

func handle_input():
	var input_direction = Vector2.ZERO
	
	# 获取输入方向
	if Input.is_action_pressed("move_up"):
		input_direction = Vector2.UP
	elif Input.is_action_pressed("move_down"):
		input_direction = Vector2.DOWN
	elif Input.is_action_pressed("move_left"):
		input_direction = Vector2.LEFT
	elif Input.is_action_pressed("move_right"):
		input_direction = Vector2.RIGHT
	
	# 更新移动
	if input_direction != Vector2.ZERO:
		direction = input_direction
		velocity = direction * speed
		update_sprite()
	else:
		velocity = Vector2.ZERO
	
	# 处理射击
	if Input.is_action_just_pressed("shoot") and can_shoot:
		shoot()

func handle_animation(delta):
	animation_timer += delta
	if animation_timer >= animation_speed:
		animation_timer = 0.0
		current_frame = (current_frame + 1) % 2
		update_sprite()

func update_sprite():
	var textures: Array[Texture2D]
	
	match direction:
		Vector2.UP:
			textures = up_textures
		Vector2.DOWN:
			textures = down_textures
		Vector2.LEFT:
			textures = left_textures
		Vector2.RIGHT:
			textures = right_textures
	
	if textures.size() > current_frame:
		sprite.texture = textures[current_frame]

func shoot():
	if not can_shoot:
		return
	
	can_shoot = false
	shoot_timer.start()
	
	# 计算子弹发射位置
	var bullet_pos = position + direction * 30
	
	# 发射信号
	player_shot.emit(bullet_pos, direction)

func _on_shoot_timer_timeout():
	can_shoot = true

func take_damage():
	health -= 1
	if health <= 0:
		die()

func die():
	player_died.emit()
	queue_free()

func upgrade():
	level += 1
	# 升级时可以增加生命值或改变外观
	if level > 1:
		health += 1
